/**
 *
 */
package com.swim.natatoriumorder.service;

import com.alibaba.fastjson.JSON;
import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.swim.common.utils.RandomGenerator;
import com.swim.common.utils.SmsUtil;
import com.swim.natatoriumgoods.entity.NatatoriumGoods;
import com.swim.natatoriumgoods.service.NatatoriumGoodsService;
import com.swim.natatoriuminfo.entity.NatatoriumInfo;
import com.swim.natatoriumorder.dao.NatatoriumOrderDao;
import com.swim.natatoriumorder.entity.NatatoriumOrder;
import com.swim.natatoriumorder.entity.OrderStudent;

import java.util.List;
import java.util.Random;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 游泳馆订单Service
 * @author tql
 * @version 2021-03-14
 */
@Service
@Transactional(readOnly=true)
public class NatatoriumOrderService extends CrudService<NatatoriumOrderDao, NatatoriumOrder> {

	@Autowired
	private OrderStudentService orderStudentService;
	@Autowired
	private NatatoriumGoodsService natatoriumGoodsService;
	/**
	 * 获取单条数据
	 * @param natatoriumOrder
	 * @return
	 */
	@Override
	public NatatoriumOrder get(NatatoriumOrder natatoriumOrder) {
		NatatoriumOrder result = super.get(natatoriumOrder);
		//查询订单学员信息
		OrderStudent orderStudent = new OrderStudent();
		orderStudent.setNatatoriumOrderId(result.getId());
		result.setOrderStudentList(orderStudentService.findList(orderStudent));
		return result;
	}

	/**
	 * 按订单ID查询对应学员
	 * @param creditRatingId
	 */
	public List<OrderStudent> orderStudentListData(String creditRatingId) {
		OrderStudent orderStudent = new OrderStudent();
		orderStudent.setNatatoriumOrderId(creditRatingId);
		List<OrderStudent> orderStudentList = orderStudentService.findList(orderStudent);
		return orderStudentList;
	}

	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param natatoriumOrder
	 * @return
	 */
	@Override
	public Page<NatatoriumOrder> findPage(Page<NatatoriumOrder> page, NatatoriumOrder natatoriumOrder) {
		return super.findPage(page, natatoriumOrder);
	}

	/**
	 * 保存数据（插入或更新）
	 * @param natatoriumOrder
	 * @return id
	 */
	@Transactional(readOnly=false)
	public NatatoriumOrder saveAuto(NatatoriumOrder natatoriumOrder) {
		//设置自动生成字段
		natatoriumOrder.setOrderNum(RandomGenerator.get8randomNumber());		// 订单号
		natatoriumOrder.setSysUserId(UserUtils.getUser().getUserCode());		// 付款人id
		natatoriumOrder.setPayerPhone(UserUtils.getUser().getLoginCode());		// 付款人手机号
		natatoriumOrder.setSettlementStatus(2L);// 结算状态 1表示可结算(专指游泳票) 2表示不可结算 3表示可结算首款 4表示可结算尾款 5表示已结算首款 6表示已结算
		natatoriumOrder.setOrderStatus(1L);		// 订单状态 1表示未付款 2表示已付款 3表示已核销 4表示已关闭
		super.save(natatoriumOrder);
//		//新增订单学员信息
//		List<OrderStudent> orderStudentList = JSON.parseArray(natatoriumOrder.getOrderStudentListStr(), OrderStudent.class);
//		if (!CollectionUtils.isEmpty(orderStudentList)) {
//			for (OrderStudent orderStudentOne : orderStudentList) {
//				orderStudentOne.setNatatoriumOrderId(natatoriumOrder.getId());
//				orderStudentOne.setNatatoriumInfoId(natatoriumOrder.getNatatoriumInfoId());
//				orderStudentService.save(orderStudentOne);
//			}
//		}
		//新增订单学员信息
		List<OrderStudent> orderStudentList = natatoriumOrder.getOrderStudentList();
		if (!CollectionUtils.isEmpty(orderStudentList)) {
			for (OrderStudent orderStudentOne : orderStudentList) {
				orderStudentOne.setNatatoriumOrderId(natatoriumOrder.getId());
				orderStudentOne.setNatatoriumInfoId(natatoriumOrder.getNatatoriumInfoId());
				orderStudentService.save(orderStudentOne);
			}
		}
		return natatoriumOrder;
	}

//	/**
//	 * 保存数据（插入或更新）
//	 * @param natatoriumOrder
//	 * @return id
//	 */
//	@Transactional(readOnly=false)
//	public NatatoriumOrder saveAuto(NatatoriumOrder natatoriumOrder) {
//		//设置自动生成字段
//		natatoriumOrder.setOrderNum(RandomGenerator.get8randomNumber());		// 订单号
//		natatoriumOrder.setSysUserId(UserUtils.getUser().getUserCode());		// 付款人id
//		natatoriumOrder.setPayerPhone(UserUtils.getUser().getLoginCode());		// 付款人手机号
//		natatoriumOrder.setSettlementStatus(2L);// 结算状态 1表示可结算(专指游泳票) 2表示不可结算 3表示可结算首款 4表示可结算尾款 5表示已结算首款 6表示已结算
//		natatoriumOrder.setOrderStatus(1L);		// 订单状态 1表示未付款 2表示已付款 3表示已核销 4表示已关闭
//		super.save(natatoriumOrder);
//		//新增订单学员信息
//		List<OrderStudent> orderStudentList = natatoriumOrder.getOrderStudentList();
//		if (!CollectionUtils.isEmpty(orderStudentList)) {
//			for (OrderStudent orderStudentOne : orderStudentList) {
//				orderStudentOne.setNatatoriumOrderId(natatoriumOrder.getId());
//				orderStudentOne.setNatatoriumInfoId(natatoriumOrder.getNatatoriumInfoId());
//				orderStudentService.save(orderStudentOne);
//			}
//		}
//		return natatoriumOrder;
//	}

//	/**
//	 * 更新订单支付状态
//	 * @param natatoriumOrderId  支付id
//	 * @param orderStatus  订单状态 1表示付款中 2表示已付款 3表示已核销 4表示已关闭
//	 * @return id
//	 */
//	public void updateOrderStatus(String natatoriumOrderId, Long orderStatus) {
//		NatatoriumOrder natatoriumOrder = super.get(natatoriumOrderId);
//		natatoriumOrder.setOrderStatus(orderStatus);// 订单状态 1表示付款中 2表示已付款 3表示已核销 4表示已关闭
//		super.update(natatoriumOrder);
//		if (orderStatus == 2) {//2表示已付款 
//			//付款成功后给用户发送核销验证码
//			String code = "";
//	        try {
//	            Random random = new Random();
//	            for (int i = 0; i < 6; i++) {
//	                code += random.nextInt(10);
//	            }
//	            // 发送验证码
//	            SmsUtil.sendSettlementCode(natatoriumOrder.getOrderNum(), UserUtils.getUser().getLoginCode(), code);
//	        } catch (Exception e) {
//	            System.out.println("发送核销码短信异常");
//	        }
//	        //把核销验证码保存到订单中
//	        natatoriumOrder.setSettlementCode(code);
//	        super.update(natatoriumOrder);
//		}
//	}

	/**
	 * 更新状态
	 * @param natatoriumOrder
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(NatatoriumOrder natatoriumOrder) {
		super.updateStatus(natatoriumOrder);
	}

	/**
	 * 删除数据
	 * @param natatoriumOrder
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(NatatoriumOrder natatoriumOrder) {
		super.delete(natatoriumOrder);
	}

	@Transactional(readOnly=false)
	public void orderPaySuccess(String outTradeNo) {
		try {
			NatatoriumOrder natatoriumOrder = new NatatoriumOrder();
			natatoriumOrder.setOrderNum(outTradeNo);
			List<NatatoriumOrder> natatoriumOrder1 = this.findList(natatoriumOrder);
			if(CollectionUtils.isNotEmpty(natatoriumOrder1)) {
				NatatoriumOrder order = natatoriumOrder1.get(0);
				if(order.getOrderStatus() == 1L) {
					//付款成功后给用户发送核销验证码
					orderPaySuccess(order);
				} else {
					logger.error("当前订单已支付");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("更新订单状态异常，e={}", e.getMessage());
		}

	}

	/**
	 * 付款成功后执行的业务逻辑
	 * @param natatoriumOrder
	 */
	public void orderPaySuccess(NatatoriumOrder natatoriumOrder) {
		String code = "";
		try {
			Random random = new Random();
			for (int i = 0; i < 6; i++) {
				code += random.nextInt(10);
			}
			// 发送核销验证码
			SmsUtil.sendSettlementCode(natatoriumOrder.getOrderNum(), natatoriumOrder.getPayerPhone(), code);
			// 用户下单后通知游泳馆
			NatatoriumInfo natatoriumInfo = natatoriumOrder.getNatatoriumInfo();//游泳馆信息 实体
			NatatoriumGoods natatoriumGoods = natatoriumOrder.getNatatoriumGoods();//游泳馆商品 实体
			SmsUtil.placeOrderNoticeNatatorium(natatoriumGoods.getName(), natatoriumInfo.getPhone());
			// 用户下单后通知平台
			SmsUtil.placeOrderNoticePlatform(natatoriumInfo.getName(), natatoriumGoods.getName(), "13912785198");
		} catch (Exception e) {
			logger.error("发送核销码短信异常");
			System.out.println("发送核销码短信异常");
		}
		//把核销验证码保存到订单中
		natatoriumOrder.setSettlementCode(code);
		//修改订单状态
		natatoriumOrder.setOrderStatus(2L);// 订单状态 1表示付款中 2表示已付款 3表示已核销 4表示已关闭
		if (natatoriumOrder.getNatatoriumGoods().getGoodsType() == 1L) {// 商品类型 1表示游泳票 2表示培训课程
			natatoriumOrder.setSettlementStatus(1L);        // 结算状态 1表示可结算(专指游泳票) 2表示不可结算 3表示可结算首款 4表示可结算尾款 5表示已结算首款 6表示已结算
		} else if (natatoriumOrder.getNatatoriumGoods().getGoodsType() == 2L) {
			natatoriumOrder.setSettlementStatus(3L);
		}
		this.update(natatoriumOrder);

		//更新商品库存
		NatatoriumGoods natatoriumGoods = natatoriumGoodsService.get(natatoriumOrder.getNatatoriumGoodId());
		natatoriumGoods.setNumber(natatoriumGoods.getNumber() - 1);
		natatoriumGoodsService.update(natatoriumGoods);
	}
}